package com.xbaoziplus.simple_spring.beans.factory.support;

import com.xbaoziplus.simple_spring.beans.BeansException;
import com.xbaoziplus.simple_spring.beans.factory.BeanFactory;
import com.xbaoziplus.simple_spring.beans.factory.config.BeanDefinition;

/**
 * @author xbaozi
 * @version 1.0
 * @classname AbstractBeanFactory
 * @date 2023-04-18  16:31
 * @description 用于访问 Spring bean 容器的根接口.
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {
    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T)getBean(name);
    }

    protected <T> T doGetBean(final String name, final Object[] args) {
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        return (T) createBean(name, beanDefinition, args);
    }

    /**
     * @description 返回给定 bean 名称的 bean 定义。子类通常应该实现缓存，因为每次需要 bean 定义元数据时都会调用此方法。
     * @author xbaozi
     * @date 2023/4/18 16:46
     * @param beanName  bean名称
     **/
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * @description 为给定的合并 bean 定义（和参数）创建一个 bean 实例。
     * @author xbaozi
     * @date 2023/4/18 16:46
     * @param beanName  bean名称
     * @param beanDefinition    bean对象
     * @param args      用显式参数创建 bean 实例时使用的参数
     **/
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;
}
